/***
 *** mullet_funcs.js
 ***
 *** Extra client-side mullet functionality contributed by Mornil.
 ***/

var atable;         /* attendance table element */
var rform;          /* raid form element (holds attendance table) */

/* Regexp for MULLET date format */
var datematch  = /^(\d+)\/(\d+) (\d+):(\d+) (am|pm)/;

var cursortcol = -1; /* What column is currently sorted? */

/*
 * Intelligent comparison function...tries to figure out automatically
 * whether we're sorting text, dates, integers, or floats.
 */
function smartsort(a, b) {
    var match1 = datematch.exec(a);
    var match2 = datematch.exec(b);

    if (match1 && match2) {
        var mon1 = parseInt(match1[1]), day1 = parseInt(match1[2]), hour1 = parseInt(match1[3]), min1 = parseInt(match1[4]), ampm1 = match1[5];
        var mon2 = parseInt(match2[1]), day2 = parseInt(match2[2]), hour2 = parseInt(match2[3]), min2 = parseInt(match2[4]), ampm2 = match2[5];

        /* Switch to 24-hour time */
        if (hour1 == 12) hour1 = 0;
        if (hour2 == 12) hour2 = 0;
        if (ampm1 == "pm") hour1 += 12;
        if (ampm2 == "pm") hour2 += 12;

        if (mon1 != mon2) return mon1 - mon2;
        if (day1 != day2) return day1 - day2;
        if (hour1 != hour2) return hour1 - hour2;
        return min1 - min2;
	} else if (a == parseFloat(a) && b == parseFloat(b)) {
		// NOTE:  Sort numbers in reverse order (i.e., highest first)
		return parseFloat(b) - parseFloat(a);
    } else {
        if (a.toUpperCase() == b.toUpperCase()) return 0;
        if (a.toUpperCase() < b.toUpperCase()) return -1;
        return 1;
    }
}


/*
 * Comparison function for the row sorting.  Input elements are arrays of the
 * form [ text, row element, attending ].  'attending' is either 1 or 0 to
 * indicate true or false; attending rows are always listed first.  Otherwise
 * we'll just compare the text.
 */
function rcomp(a, b) {
    if (a[2] == b[2])
        return smartsort(a[0], b[0]);
    else
        return b[2] - a[2];
}

function reversercomp(a, b) {
    return -1 * rcomp(a, b);
}


/* The function that does the heavy lifting */
function dosort(ev) {
    /* Browser coders, learn to follow consistent standards please... */
    ev = ev || window.event;
    var target = ev.target || ev.srcElement;
    // and now we should have the target element no matter how broken the
    // browser's DOM and event model is...

    var body = atable.tBodies[0];
    var col = target.columnid;
    var rows = body.rows;
    var sortrows = Array();             // each element is (sortkey, row element)

    /* Build our value->row mapping array */
    for (var r = 0; r < rows.length; r++) {
        var sortval = rows[r].cells[col];
        var isattending = (rows[r].className == "attending") ? 1 : 0;
        if (sortval.firstChild.nodeName.toUpperCase() == "A")
            sortval = sortval.firstChild;
        sortrows[r] = [ sortval.innerHTML, rows[r], isattending ]
    }

    /*
     * Sort it using the row comparison function above.  If this column
     * is already sorted, do a reverse sort instead.
     */
    if (col != cursortcol) {
        sortrows.sort(rcomp)
        cursortcol = col;
    } else {
        sortrows.sort(reversercomp);
        cursortcol = -1;    // If we click it again, revert to forward sort
    }

    /* Add the rows back to the table in the right order */
    for (var i = 0; i < sortrows.length; i++)
        body.appendChild(sortrows[i][1]);

    delete sortrows;

    return false;       // don't follow the link after all
}


/*
 * Initialization function (called at bottom of this file via
 * onload attribute...i.e., it will wait until the page is completely
 * loaded before running.
 */
function init() {
    var i;

    ///*
    // * This is fragile since it depends on the attendance table being the
    // * first table in the form container.  This could be simplified by giving
    // * more HTML elements ID's, but I want to initially code this with no
    // * changes required on the server side; we can clean it up later if
    // * Faykan wants to modify the server-side markup.
    // */
    //rform = document.getElementsByName("raidform").item(0);
    //for (i = 0; i < rform.childNodes.length; i++) {
    //    if (rform.childNodes[i].nodeName.toUpperCase() == "TABLE") {
    //        atable = rform.childNodes[i];
    //        break;
    //    }
    //}
    atable = document.getElementById("subs_table");
    if (!atable) return;   // couldn't find it.  :-(

    /*
     * We have the table.  Let's put it in a format we can work with a little
     * easier.
     */
    var header = document.createElement("thead");   /* new thead for first row */
    var footer = document.createElement("tfoot");   /* empty tfoot element */
    header.appendChild(atable.rows[0]);
    footer.appendChild(atable.rows[atable.rows.length-1]);
    atable.insertBefore(header, atable.firstChild);
    atable.appendChild(footer);

    /*
     * Safari used to not support table.tHead...not sure if that's still the
     * case or not; better safe than sorry.
     */
    if (atable.tHead == null)
		atable.tHead = atable.getElementsByTagName("thead").item(0);


    /* Setup each column if Faykan already has a sort link on that column */
    var hrow = atable.tHead.rows[0].cells;      // header row cells
    for (i = 0; i < hrow.length; i++) {
        if (hrow[i].firstChild.nodeName.toUpperCase() == "A") {
            hrow[i].firstChild.onclick = dosort;
            hrow[i].firstChild.columnid = i;
        }
    }
}


/* When the page finishes loading, go back and hijack its links */
window.onload = init;





/***
 *** Check all checkboxes
 *** used for administrators, to select all subscribers in an event at once.
 *** - found it somewhere online, didn't actually write it.
 ***/
checked = false;

function checkall() {
	if (checked == false) { checked = true }
	else { checked = false }

	for (var i = 0; i < document.forms['adminform'].elements.length; i++)
	{
		document.forms['adminform'].elements[i].checked = checked;
	}
}
